import { ElMessage } from 'element-plus'

const fetchutil = {
    install(obj) {
        console.log('调用了install');
        console.log(obj);
    },
    defaultErrorCatch(obj) {
        // console.log(obj);
        ElMessage({
            message: '错误：' + obj,
            type: "error",
        })
    },
    get(url, callback) {
        fetch(url, { method: 'get' }).then(resp => {
            // console.log(resp);
            resp.json().then(data => {
                callback(data)
            })
        }).catch(err => {
            // alert('报错')
            this.defaultErrorCatch(err)
        })
    },
    post(url, param, callback) {
        fetch(url, {
            method: 'post', headers: {//POST请求需要的话；亲测post请求不区分大小写，而patch区分大小写
                // 'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Type': 'application/json',
            },
            // body: 'xxx=xxx&jjj=jjj'//application/x-www-form-urlencoded数据格式
            body: JSON.stringify(param)//application/json json数据格式
        }).then(res => {
            if (!res.ok) {
                this.defaultErrorCatch(res.statusText)
                return
            }
            res.json().then(data => { callback(data) })
        }).catch(err => {
            this.defaultErrorCatch(err)
        })
    },
    uploadFile(url, formData, callback) {
        fetch(url, {
            method: 'post',
            body: formData,
            headers: {
                //'Content-Type': 'multipart/form-data'//这个属性不需要加
                'Authorization':'Bearer '+localStorage.getItem('access_token')
            }
        }).then(resp => {
            resp.json().then(resultData => {
                // console.log(resultData)
                callback(resultData)
            })
        }).catch(err => this.defaultErrorCatch(err))
    }
}

export default fetchutil